package com.farm.wda.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;

import org.apache.log4j.Logger;

import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.farm.wda.service.Doc2DocInter;
import com.farm.wda.util.FileUtil;

/**
 * 将Word文档转换成html字符串的工具类
 * 
 * @author MZULE
 * 
 */
public class Doc2DocImpl implements Doc2DocInter {
	private static final Logger log = Logger.getLogger(Doc2DocImpl.class);

	/**
	 * 将word文档转换成html文档
	 * 
	 * @param docFile
	 *            需要转换的word文档
	 * @param filepath
	 *            转换之后html的存放路径
	 * @return 转换之后的html文件
	 */
	public File convert(File docFile, File tarFile) {
		// 创建Openoffice连接
		OpenOfficeConnection con = new SocketOpenOfficeConnection(8100);
		try {
			// 连接
			con.connect();
		} catch (ConnectException e) {
			throw new RuntimeException("获取OpenOffice连接失败..." + e.getMessage());
		}
		try {
			// 创建转换器
			DocumentConverter converter = new OpenOfficeDocumentConverter(con);
			// 转换文档问html
			converter.convert(docFile, tarFile);
			log.info("成功转换：" + docFile + "转换到" + tarFile);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		} finally {
			// 关闭openoffice连接
			con.disconnect();
		}
		return tarFile;
	}

	public File convert(File docFile, String docFileTypename, File tarFile) {
		// 创建Openoffice连接
		OpenOfficeConnection con = new SocketOpenOfficeConnection(8100);
		try {
			// 连接
			con.connect();
		} catch (ConnectException e) {
			log.error("获取OpenOffice连接失败..." + e.getMessage());
		}
		try {
			// 创建转换器
			DocumentConverter converter = new OpenOfficeDocumentConverter(con);
			DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
			DocumentFormat pdfFormat = formatReg.getFormatByFileExtension(docFileTypename.toLowerCase());
			DocumentFormat docFormat = formatReg.getFormatByFileExtension(FileUtil.getExtensionName(tarFile.getName()));
			// stream 流的形式
			InputStream inputStream = new FileInputStream(docFile);
			OutputStream outputStream = new FileOutputStream(tarFile);
			// 转换文档问html
			converter.convert(inputStream, pdfFormat, outputStream, docFormat);
			log.info("成功转换：" + docFile + "转换到" + tarFile);
		} catch (Exception e) {
			log.error("转换错误" + e + "/" + docFile + "转换到" + tarFile);
			throw new RuntimeException(e);
		} finally {
			// 关闭openoffice连接
			con.disconnect();
		}
		return tarFile;
	}
}